import javafx.animation.FadeTransition;
import javafx.animation.ParallelTransition;
import javafx.animation.ScaleTransition;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import javafx.util.Duration;

public class MatchThreeGame extends Application {
    private GameBoard gameBoard;
    private GameController controller;
    private ScoreBoard scoreBoard;
    private LevelManager levelManager;
    private StackPane helpPane;
    private boolean showingHelp = false;
    private BorderPane root;
    private VBox feedbackPanel;
    private TextArea feedbackText;
    private Label comboLabel;
    private int comboCount = 0;
    private ProgressBar levelProgress;

    @Override
    public void start(Stage primaryStage) {
        // 初始化游戏组件
        levelManager = new LevelManager();
        scoreBoard = new ScoreBoard();
        gameBoard = new GameBoard(8, 8, levelManager.getCurrentLevel());
        controller = new GameController(gameBoard, scoreBoard, levelManager);

        // 设置控制器回调
        controller.setFeedbackListener(this::handleGameFeedback);
        // 初始化游戏板点击事件
        controller.setupCellSelectionHandlers();

        // 创建主界面
        StackPane rootStack = new StackPane();
        root = new BorderPane();
        root.setPadding(new Insets(10));

        // 创建帮助信息面板
        createHelpPane();

        // 将BorderPane和helpPane都添加到StackPane中
        rootStack.getChildren().addAll(root, helpPane);
        helpPane.toFront();

        // 创建右侧反馈面板
        createFeedbackPanel();

        // 顶部信息栏
        HBox topBar = createTopBar();
        root.setTop(topBar);

        // 中间游戏区域
        HBox gameArea = new HBox(20);
        gameArea.setAlignment(Pos.CENTER);
        gameArea.getChildren().addAll(gameBoard.getBoardPane(), feedbackPanel);
        root.setCenter(gameArea);

        // 底部控制栏
        HBox bottomBar = createBottomBar(primaryStage);
        root.setBottom(bottomBar);

        // 创建场景并显示
        Scene scene = new Scene(rootStack, 800, 700); // 加宽窗口以适应反馈面板
        primaryStage.setTitle("三消游戏");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    private void createFeedbackPanel() {
        feedbackPanel = new VBox(10);
        feedbackPanel.setPadding(new Insets(10));
        feedbackPanel.setMinWidth(200);
        feedbackPanel.setStyle("-fx-background-color: #f0f0f0; -fx-border-color: #ccc; -fx-border-width: 1;");

        // 连击计数器
        comboLabel = new Label("连击: 0");
        comboLabel.setFont(Font.font(16));
        comboLabel.setStyle("-fx-text-fill: #d35400;");

        // 关卡进度条
        levelProgress = new ProgressBar(0);
        levelProgress.setPrefWidth(180);

        // 反馈信息区域
        feedbackText = new TextArea();
        feedbackText.setEditable(false);
        feedbackText.setWrapText(true);
        feedbackText.setPrefRowCount(15);
        feedbackText.setStyle("-fx-font-family: 'Consolas'; -fx-font-size: 14;");

        ScrollPane scrollPane = new ScrollPane(feedbackText);
        scrollPane.setFitToWidth(true);
        scrollPane.setPrefHeight(400);

        feedbackPanel.getChildren().addAll(
                new Label("游戏反馈"),
                comboLabel,
                new Label("关卡进度"),
                levelProgress,
                scrollPane
        );
    }
    private void handleGameFeedback(String message, int score, int x, int y) {
        // 更新反馈文本
        feedbackText.appendText(message + "\n");

        // 滚动到底部
        feedbackText.setScrollTop(Double.MAX_VALUE);

        // 显示得分动画
        if (score > 0) {
            showScoreAnimation(score, x, y);
        }

        // 更新连击计数
        if (message.contains("消除")) {
            comboCount++;
            comboLabel.setText("连击: " + comboCount + " (x" + Math.min(5, 1 + comboCount/3) + ")");

            // 连击特效
            if (comboCount >= 3) {
                animateComboLabel();
            }
        } else {
            comboCount = 0;
            comboLabel.setText("连击: 0");
        }

        // 更新进度条
        levelProgress.setProgress((double)scoreBoard.getScore() / levelManager.getTargetScore());
    }
    private void showScoreAnimation(int score, int x, int y) {
        Label scoreLabel = new Label("+" + score);
        scoreLabel.setFont(Font.font(16));
        scoreLabel.setTextFill(Color.DARKGREEN);

        StackPane cell = gameBoard.getCellAt(x, y);
        cell.getChildren().add(scoreLabel);

        // 创建动画效果
        FadeTransition fade = new FadeTransition(Duration.seconds(1), scoreLabel);
        fade.setFromValue(1.0);
        fade.setToValue(0.0);

        TranslateTransition move = new TranslateTransition(Duration.seconds(1), scoreLabel);
        move.setByY(-50);

        ParallelTransition animation = new ParallelTransition(fade, move);
        animation.setOnFinished(e -> cell.getChildren().remove(scoreLabel));
        animation.play();
    }
    private void animateComboLabel() {
        ScaleTransition scale = new ScaleTransition(Duration.millis(300), comboLabel);
        scale.setFromX(1.0);
        scale.setFromY(1.0);
        scale.setToX(1.5);
        scale.setToY(1.5);
        scale.setAutoReverse(true);
        scale.setCycleCount(2);

        // 根据连击数改变颜色
        if (comboCount >= 6) {
            comboLabel.setTextFill(Color.RED);
        } else if (comboCount >= 3) {
            comboLabel.setTextFill(Color.ORANGE);
        }

        scale.play();
    }





    private void createHelpPane() {
        helpPane = new StackPane();
        helpPane.setBackground(new Background(new BackgroundFill(
                Color.rgb(0, 0, 0, 0.7), CornerRadii.EMPTY, Insets.EMPTY))); // 这里添加了缺失的右括号
        helpPane.setVisible(false);
        VBox helpContent = new VBox(20);
        helpContent.setAlignment(Pos.CENTER);
        helpContent.setPadding(new Insets(20));
        helpContent.setMaxWidth(500);
        helpContent.setStyle("-fx-background-color: white; -fx-background-radius: 10;");

        Label title = new Label("游戏玩法介绍");
        title.setFont(Font.font(24));
        title.setTextFill(Color.DARKBLUE);

        Text rules = new Text();
        rules.setFont(Font.font(16));
        rules.setTextAlignment(TextAlignment.CENTER);
        rules.setWrappingWidth(450);
        rules.setText("游戏规则：\n" +
                "1. 点击选中一个方块，再点击相邻方块可以交换位置\n" +
                "2. 当三个或更多相同颜色的方块连成一线时，它们会被消除\n" +
                "3. 消除的方块越多，得分越高\n" +
                "4. 达到目标分数即可进入下一关\n" +
                "5. 关卡越高，得分乘数越大（最高5倍）");
        Button closeButton = new Button("我知道了");
        closeButton.setOnAction(e -> toggleHelp());
        closeButton.setStyle("-fx-font-size: 16; -fx-padding: 5 15;");
        helpContent.getChildren().addAll(title, rules, closeButton);
        helpPane.getChildren().add(helpContent);
    }

    private void toggleHelp() {
        showingHelp = !showingHelp;
        helpPane.setVisible(showingHelp);
        gameBoard.getBoardPane().setDisable(showingHelp);
    }

    private HBox createTopBar() {
        HBox topBar = new HBox(20);
        topBar.setAlignment(Pos.CENTER);
        topBar.setPadding(new Insets(10));
        topBar.setBackground(new Background(new BackgroundFill(
                Color.LIGHTBLUE, CornerRadii.EMPTY, Insets.EMPTY)));

        Label scoreLabel = new Label("得分: ");
        Label scoreValue = new Label("0");
        scoreBoard.setScoreLabel(scoreValue);

        Label levelLabel = new Label("关卡: ");
        Label levelValue = new Label("1");
        levelManager.setLevelLabel(levelValue);

        Label targetLabel = new Label("目标: ");
        Label targetValue = new Label("" + levelManager.getTargetScore());
        levelManager.setTargetLabel(targetValue);

        Button helpButton = new Button("游戏帮助");
        helpButton.setOnAction(e -> toggleHelp());

        topBar.getChildren().addAll(
                scoreLabel, scoreValue,
                levelLabel, levelValue,
                targetLabel, targetValue,
                helpButton
        );
        return topBar;
    }
    private HBox createBottomBar(Stage primaryStage) {
        HBox bottomBar = new HBox(20);
        bottomBar.setAlignment(Pos.CENTER);
        bottomBar.setPadding(new Insets(10));

        Button newGameButton = new Button("新游戏");
        newGameButton.setOnAction(e -> {
            levelManager.reset();
            scoreBoard.reset();
            gameBoard = new GameBoard(8, 8, levelManager.getCurrentLevel());
            controller.setGameBoard(gameBoard);
            root.setCenter(gameBoard.getBoardPane());
        });

        Button nextLevelButton = new Button("下一关");
        nextLevelButton.setOnAction(e -> {
            levelManager.nextLevel();
            gameBoard = new GameBoard(8, 8, levelManager.getCurrentLevel());
            controller.setGameBoard(gameBoard);
            root.setCenter(gameBoard.getBoardPane());
        });

        bottomBar.getChildren().addAll(newGameButton, nextLevelButton);
        return bottomBar;
    }
    public static void main(String[] args) {
        launch(args);
    }
}
